package mq

import (
	"fmt"
	"yunpan/config"

	"github.com/streadway/amqp"
)

var conn *amqp.Connection
var channel *amqp.Channel

func initChannel() bool{
	// 判断channel是否已经创建
	if channel != nil{
		return true
	}

	// 创建conn连接
	conn,err := amqp.Dial(config.RabbitURL)
	if err != nil{
		fmt.Println(err.Error())
		return false
	}

	//打开一个channel,用于消息的发布与接收
	channel,err = conn.Channel()
	if err != nil{
		fmt.Println(err.Error())
		return false
	}

	return true
}

func Publish(exchange string,routingKey string,msg []byte) bool{
	// 确保 channel 已经初始化
	if !initChannel() {
		fmt.Println("Failed to initialize channel")
		return false
	}

	//发布
	err := channel.Publish(
		exchange,//交换机名称
		routingKey,//路由
		false,//是否转发
		false,//是否立即送达，新版本没有实际效果
		amqp.Publishing{
			ContentType: "text/plain",
			Body: msg,
		},
	)
	if err != nil{
		fmt.Printf("Failed to publish message: %s\n", err.Error())
		return false
	}
	return true
}

